package com.tjl.foodapp;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.RequestFuture;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link SearchFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SearchFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public SearchFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SearchFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SearchFragment newInstance(String param1, String param2) {
        SearchFragment fragment = new SearchFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
   EditText et_foodname_search;
    Button btn_search_head;
    RecyclerView rv_search_center;

    //上下文
    Context context;
    //请求队列
    RequestQueue queue;
   //数据源
    ArrayList<Food> list = new ArrayList<Food>();
    //适配器
    class MyAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view =  LayoutInflater.from(context).inflate(R.layout.search_item,null);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            ViewHolder viewHolder = (ViewHolder)holder;
            Food food = list.get(position);
            getImageByURL(Utils.urlBase+"image/"+food.getPic()+".jpg",viewHolder.img_food_search);
            viewHolder.tx_foodname_price_search.setText(food.getFoodname()+" "+food.getPrice());
            viewHolder.tx_kind_search.setText(food.getTypename());
            viewHolder.img_food_search.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putString("prePage","search");
                    bundle.putInt("food_id",food.getFood_id());
                    getItemShopMessage(Utils.urlBase+"and_getShopByFoodId.do?id="+food.getFood_id(),bundle);
                }
            });
        }

        @Override
        public int getItemCount() {
            return list.size();
        }
        class ViewHolder extends RecyclerView.ViewHolder{
            ImageButton img_food_search;
            TextView tx_foodname_price_search;
            TextView tx_kind_search;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                img_food_search = itemView.findViewById(R.id.img_food_search);
                tx_foodname_price_search = itemView.findViewById(R.id.tx_foodname_price_search);
                tx_kind_search = itemView.findViewById(R.id.tx_kind_search);

            }
        }
    }
    MyAdaper adaper;
    // 子页面管理器
    FragmentManager manager;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search, container, false);
        et_foodname_search = view.findViewById(R.id.et_foodname_search);
        btn_search_head = view.findViewById(R.id.btn_search_head);
        rv_search_center = view.findViewById(R.id.rv_search_center);

        context = this.getActivity();
        manager = this.getActivity().getSupportFragmentManager();
        queue = Volley.newRequestQueue(context);
        rv_search_center.setLayoutManager(new LinearLayoutManager(context));
        adaper = new MyAdaper();
        rv_search_center.setAdapter(adaper);
        btn_search_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String foodname = et_foodname_search.getText().toString();
                getArrayList(Utils.urlBase+"and_getFoodByFoodName.do?foodname="+foodname);
            }
        });
        //初始化时加载全部数据
        getArrayList(Utils.urlBase+"and_getFoodByFoodName.do?foodname=");

        return view;
    }
    public void getImageByURL(String url,ImageButton imageButton){
        int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024);
        int cachSize = maxMemory/8;
        LruCache<String, Bitmap> lruCache = new LruCache<String,Bitmap>(cachSize);
        ImageLoader.ImageCache imageCache = new ImageLoader.ImageCache() {
            @Override
            public Bitmap getBitmap(String s) {
                return lruCache.get(s);
            }

            @Override
            public void putBitmap(String s, Bitmap bitmap) {
                lruCache.put(s,bitmap);
            }
        };
        ImageLoader loader = new ImageLoader(queue,imageCache);
        ImageLoader.ImageListener listener
                = ImageLoader.getImageListener(imageButton,
                R.drawable.ic_launcher_background,
                R.drawable.ic_launcher_foreground);
        loader.get(url,listener);
    }
    public void getArrayList(String url){
        Response.Listener listener1 = new Response.Listener(){

            @Override
            public void onResponse(Object o) {
                list = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().fromJson(o.toString(),new TypeToken<ArrayList<Food>>(){}.getType());
                adaper.notifyDataSetChanged();
            }
        };
        Response.ErrorListener listener2 = new Response.ErrorListener(){

            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(context,"网络连接失败",Toast.LENGTH_LONG).show();
            }
        };
        JsonRequest request = new JsonArrayRequest(url,listener1,listener2);
        queue.add(request);
    }
    public void getItemShopMessage(String url,Bundle bundle){
        Response.Listener listener1 = new Response.Listener() {
            @Override
            public void onResponse(Object o) {
                Shop shop = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().fromJson(o.toString(),Shop.class);
                bundle.putInt("shop_id",shop.getShop_id());
                changeFragment(new FoodDetailFragment(),bundle,"fooddetail");
            }
        };
        Response.ErrorListener listener2 = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(context,"网络连接失败",Toast.LENGTH_LONG).show();
            }
        };
        JsonRequest request = new JsonObjectRequest(url,null,listener1,listener2);
        queue.add(request);
    }
    public void changeFragment(Fragment fragment,Bundle bundle,String tag){
        //清空子页面栈
        for(int i=0,count = manager.getBackStackEntryCount();i<count;i++){
            manager.popBackStack();
        }
        //创建一个子页面的事务，以便切换子页面
        FragmentTransaction transaction = manager.beginTransaction();
        //设置子页面的初始化参数
        fragment.setArguments(bundle);
        //切换子页面，让子页面显示到主页面的指定位置
        transaction.add(R.id.linear_fragment,fragment);
        //给栈中的子页面一个标签
        transaction.addToBackStack(tag);
        //提交事务
        transaction.commit();
    }
}